import store from '@/repo/store/store'
import {universityActionTypes} from "@/repo/store/university";
import TeamAPI from "@/repo/api/TeamAPI";
import Vue from 'vue';
import {Dialog} from 'vant'
import {universityTypes} from "../../repo/store/university";
import {isChinese} from "../../utils/util";
import UserBiz from "@/biz/UserBiz";


Vue.use(Dialog);

//获取当前用户角色 0为成员 1为普通管理员 2为超级管理员
const roleType = store.getters.enterpriseRoleInfo.roleType

const fixNickname = function (nickname) {
  if (isChinese(nickname)) {
    if (nickname.length > 4) {
      nickname = nickname.substring(0, 3)
      nickname += '...'
    }
    return nickname
  } else {
    if (nickname.length > 6) {
      nickname = nickname.substring(0, 6)
      nickname += '...'
    }
    return nickname
  }
}

//获取成员学习数据
const getChartUserData = function (teamId) {
  return new Promise((resolve, reject) => {
    Promise.all([
      TeamAPI.learnValueList(teamId, 0, 1, 5),
      TeamAPI.getExamRatio(teamId, 0),
      TeamAPI.courseCntList(teamId, 0, 1, 5),
      TeamAPI.certCntList(teamId, 0, 1, 5)]).then((res) => {

      let learnValueList = res[0].responseData.list
      let examRatioList = res[1].responseData
      let courseList = res[2].responseData.list
      let certList = res[3].responseData.list

      let userIds = fixUserIds([learnValueList, courseList, certList])

      UserBiz.getUserMap(userIds).then((userData) => {

        let learnChartList = []
        let courseChartList = []
        let certChartList = []
        let testChartList = []

        learnValueList.forEach((item) => {
          let user = userData[item.userid]
          learnChartList.push({"名字": fixNickname(user.nickname), "学习值": item.learnValue})
        })
        courseList.forEach((item) => {
          let user = userData[item.userid]
          courseChartList.push({"名字": fixNickname(user.nickname), "课程": item.cnt})
        })
        certList.forEach((item) => {
          let user = userData[item.userid]
          certChartList.push({"名字": fixNickname(user.nickname), "证书": item.cnt})
        })
        let passCount = 0
        let failCount = 0
        examRatioList.forEach((item) => {
          if (item.exam_result === 1) {
            passCount = item.count
          } else if (item.exam_result === 2) {
            failCount = item.count
          }
        })
        testChartList = [{"结果": "通过", "次数": passCount}, {"结果": "不通过", "次数": failCount}]

        let finalData = {
          "learnCountList": learnChartList,
          "courseCountList": courseChartList,
          "certCountList": certChartList,
          "testCountList": testChartList,
        }
        resolve(finalData)

      }).catch((error) => {
        reject(error)
      })

    }).catch((error) => {
      reject(error)
    })

  })

}
//获取汇总成员数据
const getSummaryChartUserData = function (teamId) {
  return new Promise((resolve, reject) => {
    Promise.all([
      TeamAPI.learnValueList(teamId, 1, 1, 5),
      TeamAPI.getExamRatio(teamId, 1),
      TeamAPI.getFunnelData(teamId, 1),
      TeamAPI.courseCntList(teamId, 1, 1, 5),
      TeamAPI.certCntList(teamId, 1, 1, 5)]).then((res) => {

      let learnValueList = res[0].responseData.list
      let examRatioList = res[1].responseData
      let funnelData = res[2].responseData
      let courseList = res[3].responseData.list
      let certList = res[4].responseData.list

      let userIds = fixUserIds([learnValueList, courseList, certList])

      UserBiz.getUserMap(userIds).then((userData) => {

        let learnChartList = []
        let courseChartList = []
        let certChartList = []
        let testChartList = []
        let funnelChartList = []
        learnValueList.forEach((item) => {
          let user = userData[item.userid]
          learnChartList.push({"名字": fixNickname(user.nickname), "学习值": item.learnValue})
        })
        courseList.forEach((item) => {
          let user = userData[item.userid]
          courseChartList.push({"名字": fixNickname(user.nickname), "课程": item.cnt})
        })
        certList.forEach((item) => {
          let user = userData[item.userid]
          certChartList.push({"名字": fixNickname(user.nickname), "证书": item.cnt})
        })
        let passCount = 0
        let failCount = 0
        examRatioList.forEach((item) => {
          if (item.exam_result === 1) {
            passCount = item.count
          } else if (item.exam_result === 2) {
            failCount = item.count
          }
        })
        testChartList = [{"结果": "通过", "次数": passCount}, {"结果": "不通过", "次数": failCount}]
        funnelChartList = [{'类型': '学习课程', '数值': funnelData.course}, {
          '类型': '参加考试',
          '数值': funnelData.exam
        }, {'类型': '领取证书', '数值': funnelData.certificate}]
        let finalData = {
          "learnCountList": learnChartList,
          "courseCountList": courseChartList,
          "certCountList": certChartList,
          "testCountList": testChartList,
          "funnelCountList": funnelChartList
        }
        resolve(finalData)

      }).catch((error) => {
        reject(error)
      })

    }).catch((error) => {
      reject(error)
    })

  })

}
//获取汇总门店学习数据
const getSummaryChartTeamData = function (teamId) {

  return new Promise((resolve, reject) => {
    Promise.all([
      TeamAPI.learnValueListTeam(teamId, 1, 5),
      TeamAPI.getExamRatio(teamId, 1),
      TeamAPI.getFunnelData(teamId, 1),
      TeamAPI.courseCntListTeam(teamId, 1, 5),
      TeamAPI.certCntListTeam(teamId,1, 5)]).then((res) => {

      let learnValueList = res[0].responseData.list
      let examRatioList = res[1].responseData
      let funnelData = res[2].responseData
      let courseList = res[3].responseData.list
      let certList = res[4].responseData.list

      let enterpriseIds = fixEnterpriseIds([learnValueList, courseList, certList])

      getEnterpriseInfoMapByIds(enterpriseIds).then((enterpriseMap) => {
        let learnChartList = []
        let courseChartList = []
        let certChartList = []
        let testChartList = []
        let funnelChartList = []
        learnValueList.forEach((item) => {
          let enterprise = enterpriseMap[item.enterpriseId]
          learnChartList.push({"名字": fixNickname(enterprise.enterpriseName), "学习值": item.learnValue})
        })
        courseList.forEach((item) => {
          let enterprise = enterpriseMap[item.enterpriseId]
          courseChartList.push({"名字": fixNickname(enterprise.enterpriseName), "课程": item.cnt})
        })
        certList.forEach((item) => {
          let enterprise = enterpriseMap[item.enterpriseId]
          certChartList.push({"名字": fixNickname(enterprise.enterpriseName), "证书": item.cnt})
        })
        let passCount = 0
        let failCount = 0
        examRatioList.forEach((item) => {
          if (item.exam_result === 1) {
            passCount = item.count
          } else if (item.exam_result === 2) {
            failCount = item.count
          }
        })
        testChartList = [{"结果": "通过", "次数": passCount}, {"结果": "不通过", "次数": failCount}]
        funnelChartList = [{'类型': '学习课程', '数值': funnelData.course}, {
          '类型': '参加考试',
          '数值': funnelData.exam
        }, {'类型': '领取证书', '数值': funnelData.certificate}]
        let finalData = {
          "learnCountList": learnChartList,
          "courseCountList": courseChartList,
          "certCountList": certChartList,
          "testCountList": testChartList,
          "funnelCountList": funnelChartList
        }
        resolve(finalData)
      }).catch((error) => {
        reject(error)
      })

    }).catch((error) => {
      reject(error)
    })

  })

}

//获取团队成员学习值排行榜
const getRankingData = function (teamId, isSummary, page = 1) {
  return new Promise((resolve, reject) => {

    TeamAPI.learnValueList(teamId, isSummary, page, 20).then((res) => {
      let learnValueList = res.responseData.list
      let userIds = []
      learnValueList.forEach((item) => {
        userIds.push(item.userid)
      })
      UserBiz.getUserMap(userIds).then((userData) => {
        learnValueList.forEach((item) => {
          let user = userData[item.userid]
          item.nickname = user.nickname
          item.pic = user.pic
        })
        resolve(learnValueList)
      }).catch((error) => {
        reject(error)
      })
    }).catch((error) => {
      reject(error)
    })
  })

}

//获取团队成员列表
const getTeamMemberList = function (teamId) {
  return new Promise((resolve, reject) => {

    TeamAPI.getTeamMember(teamId).then((res) => {
      let memberList = res.responseData.list
      memberList.sort(function (a, b) {
        return b.roleType - a.roleType
      })
      let userIds = []
      memberList.forEach((t) => {
        userIds.push(t.userid)
      })
      UserBiz.getUserMap(userIds).then((user) => {
        for (let index in memberList) {
          let userInfo = memberList[index]
          let dataUser = user[userInfo.userid] || {}
          userInfo.nickname = dataUser.nickname
          userInfo.pic = dataUser.pic
          userInfo.learnValue = dataUser.learnValue
        }
        resolve(memberList)

      }).catch((error) => {
        reject(error)
      })

    }).catch((error) => {
      reject(error)
    })

  })

}

//通过门店ID列表获取门店信息数据返回一个以id为key的Map
const getEnterpriseInfoMapByIds = function (enterpriseIds) {
  return new Promise((resolve, reject) => {
    let enterpriseList = store.getters.enterpriseList
    if (enterpriseList.length === 0) {
      store.dispatch(universityActionTypes.UPDATE_UNIVERSITY_ENTERPRISE_LIST).then((val) => {
        if (enterpriseIds.length === 0) {
          resolve(val)
        } else {
          resolve(fixEnterpriseData(val, enterpriseIds))
        }
      }).catch((error) => {
        reject(error)
      })
    } else {
      if (enterpriseIds.length === 0) {
        resolve(enterpriseList)
      } else {
        resolve(fixEnterpriseData(enterpriseList, enterpriseIds))
      }
    }
  })
}
//getEnterpriseInfoMapByIds方法的数据组合
const fixEnterpriseData = function (enterpriseList, enterpriseIds) {
  let resultData = {}
  enterpriseIds.forEach((id) => {
    enterpriseList.forEach((enterprise) => {
      if (id === enterprise.id) {
        resultData[id] = enterprise
      }
    })
  })
  return resultData
}
//管理员操作人员的actionSheet列表
const getEditUserItems = function (user) {
  let actions = []
  if (roleType === 2) {
    //超级管理员权限
    if (user.roleType === 1) {
      //对象为管理员
      let permission = user.permission || "[1, 2]"
      permission = JSON.parse(permission)
      if (permission.length > 0) {
        //权限已打开
        actions = [{name: '关闭添加/移除成员权限', index: 0}]
      } else {
        actions = [{name: '开启添加/移除成员权限', index: 0}]
      }
    } else {
      //对象为成员
      if (user.parentEnterpriseId === 0) {
        //顶部企业不能任命管理员
        actions = [{name: '更换企业', index: 2}, {name: '移除员工', index: 3}]
      } else {
        actions = [{name: '任命为管理员', index: 1}, {name: '更换企业', index: 2}, {name: '移除员工', index: 3}]
      }
    }
  } else {
    //普通管理员权限
    actions = [{name: '移除员工', index: 3}]
  }
  return actions
}

//设置管理员邀请踢人权限
const modifyManagerPermission = function (user) {
  return new Promise((resolve, reject) => {
    let permission = user.permission || "[1, 2]"
    permission = JSON.parse(permission)
    Dialog.confirm({
      title: '提醒',
      message: `是否${permission.length > 0 ? '关闭' : '开启'}${user.nickname}的添加/移除成员权限?`,
    }).then(() => {
      TeamAPI.modifyManagerPermission(user.userid, permission.length > 0 ? [] : [1, 2]).then((res) => {
        resolve()
      }).catch(() => {
        reject()
      })
    })
  })
}

//任命管理员
const setManager = function (user) {

  return new Promise((resolve, reject) => {
    Dialog.confirm({
      title: '提醒',
      message: `是否任命${user.nickname}为管理员替换原管理员?`,
    }).then(() => {
      TeamAPI.superSetManager(user.userid).then((res) => {
        resolve()
      }).catch(() => {
        reject()
      })
    })
  })

}

//踢人 .
const kickMember = function (user) {
  return new Promise((resolve, reject) => {
    Dialog.confirm({
      title: '提醒',
      message: `是否踢出${user.nickname}?`,
    }).then(() => {
      TeamAPI.kickMember(user.userid).then((res) => {
        resolve()
      }).catch(() => {
        reject()
      })
    })
  })
}

//通过多个数据接口提取不重复的userId
const fixUserIds = function (list) {
  let userIds = []
  for (let idx in list) {
    let curList = list[idx]
    curList.forEach((item) => {
      if (userIds.indexOf(item.userid) === -1) {
        userIds.push(item.userid)
      }
    })
  }
  return userIds
}
//通过多个数据接口提取不重复的enterpriseId
const fixEnterpriseIds = function (list) {
  let enterpriseIds = []
  for (let idx in list) {
    let curList = list[idx]
    curList.forEach((item) => {
      if (enterpriseIds.indexOf(item.enterpriseId) === -1) {
        enterpriseIds.push(item.enterpriseId)
      }
    })
  }
  return enterpriseIds
}

export default {
  getChartUserData,
  getSummaryChartUserData,
  getSummaryChartTeamData,
  getRankingData,
  getTeamMemberList,
  roleType,
  getEditUserItems,
  modifyManagerPermission,
  setManager,
  kickMember,
  getEnterpriseInfoMapByIds
}
